package eng.jTrussSolver.Force;

import java.text.NumberFormat;
import java.text.ParseException;
import java.util.HashMap;

import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class ForceHashMap extends HashMap<Integer, ForceData> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int _forcecounter;

	public ForceHashMap()
	{

		_forcecounter = 0;
	}

	public void addForce(ForceData forcedata) {

		this.put(this._forcecounter, forcedata);
		this._forcecounter = _forcecounter + 1 ;
	}
	
	
	public void setForce(ForceData forcedata) {
		
		this.remove(forcedata.getForceID());
		this.put(forcedata.getForceID(), forcedata);
		
	}
	
	public void removeForce(int key) {
		this.remove(key);
	}

	public int getNodeForceHashKey() {
		return _forcecounter;
	}
	
	public int getNodeForceCount() {

		return this.size();
	}
	
	public int getStringElementID(String jListElement) {
		int ID = 0;
		try {
			ID = ((Number)NumberFormat.getInstance().parse(jListElement)).intValue();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return ID;
	}

	public double calcNodeResultantX(int key) {
		double NodeResultantX = 0;
		for (int i=0; i<this.size(); i++ ) {
			if (this.get(i).getNodeIDofForce()== key ) {
				NodeResultantX = NodeResultantX + (this.get(i).getMagnitude()* Math.cos(this.get(i).getAngle_Rad()));
			}
		}
		return NodeResultantX;
	}

	public double calcNodeResultantY(int key) {
		double NodeResultantY = 0;
		for (int i=0; i<this.size(); i++ ) {
			if (this.get(i).getNodeIDofForce() == key ) {
				NodeResultantY = NodeResultantY + (this.get(i).getMagnitude() * Math.sin(this.get(i).getAngle_Rad()));
			}
		}
		return NodeResultantY;
	}

	/**
	 * Code for Forces
	 * @param doc
	 * @return
	 */
	public Element prepareXMLElement(Document doc) {
		
		Element F = doc.createElement("Forces");


		for (Integer i : this.keySet()) {

			Element forceElement = doc.createElement("Force");
			F.appendChild(forceElement);

			Element g = doc.createElement("ForceID");
			g.appendChild(doc.createTextNode(String.valueOf((this.get(i).getForceID()))));	
			forceElement.appendChild(g);

			Element el = doc.createElement("actionNode");
			el.appendChild(doc.createTextNode(String.valueOf(this.get(i).getNodeIDofForce())));
			forceElement.appendChild(el);

			Element c = doc.createElement("ForceValue");
			c.appendChild(doc.createTextNode(String.valueOf(this.get(i).getMagnitude())));
			forceElement.appendChild(c);

			Element an = doc.createElement("ForceAngle");
			an.appendChild(doc.createTextNode(String.valueOf(this.get(i).getAngle_Degrees())));
			forceElement.appendChild(an);
		}
		return F;
	}

	/**
	 * Clears() Hashmap and also resets counter.
	 */
	public void clear()
	{
		super.clear();
		this._forcecounter=0;
	}

	
	
}
